const Koa = require('koa')
const app = new Koa()
const pageRouter = require('./routers/dev.ssr')
// const router = require('koa-router')()
const isDev = process.env.NODE_ENV === 'development'
// // logger

// app.use(async (ctx, next) => {
//   await next()
//   const rt = ctx.response.get('X-Response-Time')
//   console.log(`${ctx.method} ${ctx.url} - ${rt}`)
// })

// // x-response-time

// app.use(async (ctx, next) => {
//   const start = Date.now()
//   await next()
//   const ms = Date.now() - start
//   ctx.set('X-Response-Time', `${ms}ms`)
// })
app.use(async (ctx, next) => {
  try {
    console.log(`request with path ${ctx.path}`)
    await next()
  } catch (err) {
    console.log(err)
    ctx.status = 500
    if (isDev) {
      ctx.body = err.message
    } else {
      ctx.body = 'please try again later'
    }
  }
})
// response

// add url-route:
// router.get('/hello/:name', async (ctx, next) => {
//   console.log(ctx.params)
//   var name = ctx.params.name
//   ctx.response.body = `<h1>Hello, ${name}!</h1>`
// })

// router.get('/', async (ctx, next) => {
//   ctx.response.body = '<h1>Index</h1>'
// })

// // add router middleware:
// app.use(router.routes())
// app.use(async ctx => {
//   ctx.body = 'Hello World'
// })

app.use(pageRouter.routes()).use(pageRouter.allowedMethods())
const HOST = process.env.HOST || '0.0.0.0'
const PORT = process.env.PORT || 3333
app.listen(PORT, HOST, () => {
  console.log(`listening ${HOST}:${PORT}...`)
})
